//引入axios
import axios from "axios";
import Element from "element-ui";
import router from "./router";
import store from "./store";

//自动添加前缀
axios.defaults.baseURL = "http://localhost:8081";

//axios请求前置拦截
axios.interceptors.request.use((config) => {
  console.log(config);
  return config;
});
//axios请求后置拦截
axios.interceptors.response.use(
  (response) => {
    let res = response;

    console.log(res.data);
    if (response.data.code == 200) {
        //成功则放行
      return response;
    } else {
      // 弹窗异常信息
      Element.Message({
        message: response.data.msg,
        type: "error",
        duration: 2 * 1000,
      });
      //提前返回不允许 登录后面的代码
      return Promise.reject(response.data.msg);
    }
  },
  //报错处理
  (error) => {
    console.log(error.response);
    if (error.response.data) {
      error.message = error.response.data.msg;
    }
    //用户名错误移除浏览器信息
    if (error.response.status === 400) {
      store.commit("REMOVE_INFO");
      router.push("/login");
    }
    // 弹窗异常信息
    Element.Message({
      message: error.message,
      type: "error",
      duration: 2 * 1000,
    });
    //提前返回不允许 登录后面的代码
    return Promise.reject(error);
  }
);
